﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QLBH.DataModel;
using System.Data;

namespace QLBH.Model.Controller
{
    public class PhieuMuaHangController : QLBHEntityBase<PHIEUMUAHANG>
    {
        public static QLBHEntityBase<PHIEUMUAHANG> GetInstance()
        {
            return new PhieuMuaHangController();
        }
        public override PHIEUMUAHANG Add(PHIEUMUAHANG entity)
        {
            return base.Add(entity);
        }
        public override PHIEUMUAHANG Edit(PHIEUMUAHANG entity)
        {
            try
            {
                PHIEUMUAHANG obj = FindBy(e => e.MUAHANGID == entity.MUAHANGID).FirstOrDefault();
                this.Context.ObjectStateManager.ChangeObjectState(obj, EntityState.Modified);

                // apply status for all children
                var childs = QLPhieuMuaHangChiTietController.GetInstance().FindBy(mhct => mhct.MUAHANGID == entity.MUAHANGID);

                if (childs != null)
                {
                    foreach (PHIEUMUAHANGCT ct in childs)
                    {
                        //PHIEUMUAHANGCT o = QLPhieuMuaHangChiTietController.Instance.FindBy(e => e.MUAHANGID == ct.MUAHANGID).FirstOrDefault();

                        if (entity.PHIEUMUAHANGCTs.Where(c => c.MHID == ct.MHID).FirstOrDefault() == null)
                        {
                            this.Context.ObjectStateManager.ChangeObjectState(ct, EntityState.Deleted);
                        }
                        else
                        {
                            this.Context.ObjectStateManager.ChangeObjectState(ct, EntityState.Modified);
                        }
                    }
                }

                Save();
                return entity;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            
        }        
    }
}
